package com.lagou.edu.service.impl;

import com.lagou.edu.util.CodeType;
import com.lagou.edu.entity.UserAuthCode;
import com.lagou.edu.service.EmailCodeService;
import com.lagou.edu.service.EmailFeignClient;
import com.lagou.edu.dao.LagouAuthCodeDao;
import com.lagou.edu.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author weijie
 * @date 2020/5/26 12:42
 */
@Service
@Slf4j
public class EmailCodeServiceImpl implements EmailCodeService {

    @Autowired
    LagouAuthCodeDao lagouAuthCodeDao;
    @Autowired
    EmailFeignClient emailFeignClient;
    @Value("${code.expire}")
    Integer expire;

    @Override
    public Result createCode(String email) {
        //1.产生随机的验证码
        String code = String.valueOf((int)((Math.random()*9+1)*100000));
        //2.将验证码存储到数据库中
        UserAuthCode authCode = new UserAuthCode();
        authCode.setCode(code);
        authCode.setEmail(email);
        authCode.setCreatetime(new Date());
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE, expire);
        authCode.setExpiretime(instance.getTime());
        lagouAuthCodeDao.save(authCode);
        //3.发送邮件
        Boolean isSuccess = emailFeignClient.sendEmail(email, code);
        if (isSuccess){
            return Result.ok(code);
        }else{
            return Result.error("邮件发送失败");
        }
    }

    @Override
    public Integer checkCode(String email, String code) {
        //从数据库中查询验证码
        List<UserAuthCode> lagouAuthCodeList = lagouAuthCodeDao.findLagouAuthCodeByEmailAndCodeOrderByExpiretimeDesc(email, code);
        if (lagouAuthCodeList.isEmpty()){
            return CodeType.WRONG.getCode();
        }else{
            UserAuthCode lagouAuthCode = lagouAuthCodeList.get(0);
            Date expiretime = lagouAuthCode.getExpiretime();
            long currentTimeMillis = System.currentTimeMillis();
            long expiretimeMills = expiretime.getTime();
            if ((expiretimeMills - currentTimeMillis)/1000 > expire*60){
                return CodeType.TIME_OUT.getCode();
            }else{
                return CodeType.RIGHT.getCode();
            }
        }
    }
}
